<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class UserController extends Controller
{
    public function __construct()
    {
        $this -> middleware('login');
    }
    //用户添加add
    public function add()
    {
      return view('admin.user.add', ['title' => '用户添加']);
    }

    public function insert(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:6|max:18',
            'password' => 'required',
            'repassword' => 'same:password',
            'email' => 'email',
            'phone' => 'digits:11',
            'pic' => 'image|max:2048',
        ], [
            'name.required' => '用户名不能为空',
            'name.min' => '用户名最少6位',
            'name.max' => '用户名最多18位',
            'password.required' => '密码不能为空',
            'repassword.same' => '密码不一致',
            'email' => '邮箱格式不正确',
            'phone.digits' => '请输入正确的手机号',
            'pic.image' => '请上传一张图片作为头像',
            'pic.max' => '图片最大2M',
        ]);

        $data = $request -> except('_token');
        // 处理密码字段
        $str = Crypt::encryptString($data['password']);
        $userData['password'] = $str;

        if($request -> file('pic') -> isValid())
        {
           // 处理头像
            $extension = $request -> file('pic') -> getClientOriginalExtension();
            // echo $extension;
            $filename = mt_rand(10000000, 99999990).'.'.$extension;
            $dir = './uploads/avatar/'; 
            $request -> file('pic') -> move($dir, $filename);

            $userInfoData['pic'] = '/uploads/avatar/'.$filename;
        }else
        {
            $userinfoData['pic'] = '/uploads/avatar/default.jpg';
        }

        $userData['name'] = $data['name'];
        $userData['email'] = $data['email'];
        $userData['phone'] = $data['phone'];
        $userData['token'] = str_random(50);
        $userData['airline'] = 0;
        $userData['status'] = 0;
        $time = date('Y-m-d H:i:s');
        $userData['created_at'] = $time;
        $userData['updated_at'] = $time;

        // 添加数据
        $userId = DB::table('users') -> insertGetId($userData);

        if($userId)
        {
            $userInfoData['user_id'] = $userId;
            $userInfoData['created_at'] = $time;
            $userInfoData['updated_at'] = $time;

            $res = DB::table('users_info') -> insert($userInfoData);

            if($res)
            {
                return redirect('/admin/user/index') -> with(['info' => '添加成功']);
            }else
            {
                return back() -> with(['info' => '添加失败']);
            }
        }
    }

    public function index(Request $request)
    {
        $num = $request -> input('num', 2);
        $keywords = $request -> input('keywords', '');

        $data = DB::table('users') -> select('users.*', 'users_info.pic') -> leftJoin('users_info', 'users.id', '=', 'users_info.user_id') -> where('name', 'like', '%'.$keywords.'%') -> paginate($num);

        return view('admin.user.index', ['data' => $data, 'request' => $request -> all(), 'title' => '用户列表']);
    }

    // ajax修改用户名
    public function changeName(Request $request)
    {
        $id = $request -> id;
        $name = $request -> name;

        $res = DB::table('users') -> where('id', $id) -> update(['name' => $name]);
        if($res)
        {
            return 1;
        }else
        {
            return 0;
        }
    }

    // ajax修改禁用/启用
    public function changeStatus(Request $request)
    {
        $status = $request -> status;

        if($status == '启用')
        {
           $res = DB::table('users') -> where('id', $request -> id) -> update(['status' => 0]);
           return 1;
        }
        if($status == '禁用')
        {
           DB::table('users') -> where('id', $request -> id) -> update(['status' => 1]);
           return 0;
        }

    }

    public function edit($id)
    {
        $data = DB::table('users')
         -> select('users.*', 'users_info.pic') 
         -> leftJoin('users_info', 'users.id', '=', 'users_info.user_id') 
         -> where('users.id', $id) 
         -> first();

        return view('admin.user.edit', ['title' => '用户编辑', 'data' => $data]);
    }

    public function update(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:6|max:18',
            'password' => 'required',
            'repassword' => 'same:password',
            'email' => 'email',
            'phone' => 'digits:11',
            'pic' => 'image|max:2048',
        ], [
            'name.required' => '用户名不能为空',
            'name.min' => '用户名最少6位',
            'name.max' => '用户名最多18位',
            'password.required' => '密码不能为空',
            'repassword.same' => '密码不一致',
            'email' => '邮箱格式不正确',
            'phone.digits' => '请输入正确的手机号',
            'pic.image' => '请上传一张图片作为头像',
            'pic.max' => '图片最大2M',
        ]);

        $data = $request -> except('_token', 'repassword');
        $str = Crypt::encryptString($data['password']);
        $id = $data['id'];
        $time = date('Y-m-d H:i:s');

        if($request -> file('pic') -> isValid())
        {
           // 处理头像
            $extension = $request -> file('pic') -> getClientOriginalExtension();
            // echo $extension;
            $filename = mt_rand(10000000, 99999990).'.'.$extension;
            $dir = './uploads/avatar/'; 
            $request -> file('pic') -> move($dir, $filename);

            $userInfoData['pic'] = '/uploads/avatar/'.$filename;
            $userInfoData['updated_at'] = $time;

            // 获取原来的图片
            $oldPic = DB::table('users_info') -> where('user_id', $id) -> first() -> pic;
            if(!empty($oldPic))
            {
                if($oldPic != '/uploads/avatar/default.jpg')
                {
                    if(file_exists('.'.$oldPic))
                    {
                        unlink('.'.$oldPic);
                    }
                }
            }

            DB::table('users_info') -> where('user_id', $id) -> update($userInfoData);

        }else
        {
            $userinfoData['pic'] = '/uploads/avatar/default.jpg';
        }

        $userData['name'] = $data['name'];
        $userData['password'] = $str;
        $userData['email'] = $data['email'];
        $userData['phone'] = $data['phone'];
        $userData['updated_at'] = $time;

        // 添加数据
        $res = DB::table('users') -> where('id', $id) -> update($userData);

        if($res)
        {
            return redirect('/admin/user/index') -> with(['info' => '修改成功']);
        }else
        {
            return back() -> with(['info' => '修改失败']);
        }
    }

    public function delete($id)
    {
        $oldPic = DB::table('users_info') -> where('user_id', $id) -> first() -> pic;
        $res = DB::table('users') -> where('id', $id) -> delete();

        if($res)
        {
            DB::table('users_info') -> where('user_id', $id) -> delete();
            if(!empty($oldPic))
            {
                if($oldPic != '/uploads/avatar/default.jpg')
                {
                    if(file_exists('.'.$oldPic))
                    {
                        unlink('.'.$oldPic);
                    }
                }
            }
        }

        if($res)
        {
            return redirect('/admin/user/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }


}
